// 获取 URL 详细信息的函数
function getUrlDetails(url) {
  try {
    const urlObj = new URL(url);

    return {
      hostname: urlObj.hostname,
      port:
        urlObj.port ||
        (urlObj.protocol === "http:"
          ? 80
          : urlObj.protocol === "https:"
            ? 443
            : null),
      protocol: urlObj.protocol,
      pathname: urlObj.pathname,
      host: urlObj.host,
      hash: urlObj.hash,
      search: urlObj.search,
    };
  } catch (error) {
    console.error("Invalid URL:", error);
    return null;
  }
}

const API_URL = import.meta.env.VITE_APP_API_URL;
const API_PORT = import.meta.env.VITE_APP_API_PORT;
let protocol = location.protocol;
let host = location.host;
let hostname = location.hostname;
let port =
  location.port ||
  (protocol === "http:" ? 80 : protocol === "https:" ? 443 : null);
let BASE_URL = API_URL || `${protocol}//${hostname}:${API_PORT || port}`;

// 根据环境设置协议、主机名和端口
if (
  process.env.NODE_ENV !== "production" &&
  process.env.NODE_ENV !== "development"
) {
  BASE_URL = API_URL; // 默认 API_URL
} else {
  const urlDetails = getUrlDetails(BASE_URL);

  if (urlDetails) {
    protocol = urlDetails.protocol;
    hostname = urlDetails.hostname;
    host = urlDetails.host;
  }
}

// 设置 WebSocket 协议和端口
let wsProtocol = BASE_URL.includes("https:") ? "wss:" : "ws:";
let streamRelayWsPort = BASE_URL.includes("https:") ? 2030 : 2018;
let webRtcStreamerPort = BASE_URL.includes("https:") ? 8000 : 8001;

// 导出需要的配置
export {
  BASE_URL,
  hostname,
  host,
  protocol,
  wsProtocol,
  streamRelayWsPort,
  webRtcStreamerPort,
};
